package com.group3.service.mqservice;

import com.group3.Feign.PaymentSeviceFeign;
import com.group3.Feign.ProductServiceFeign;
import com.group3.Feign.UserServiceFeign;
import com.group3.Feign.CacheServiceFeign;

import com.group3.common.message.SeckillOrderMessage;
import com.group3.common.topic.NotificationTopic;
import com.group3.model.Order;
import com.group3.model.Product;
import com.group3.model.User;
import com.group3.service.OrderSevice;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import  com.group3.common.topic.SeckillTopic;
@Service
// 秒杀订单MQ消费者
@Slf4j
@RocketMQMessageListener(topic = SeckillTopic.SECKILL_ORDER_CREATE, consumerGroup = "seckill-order-group")
public class SeckillOrderListener implements RocketMQListener<SeckillOrderMessage> {

    @Autowired
    UserServiceFeign userServiceFeign ;
    @Autowired
    ProductServiceFeign productServiceFeign ;
    @Autowired
    OrderSevice orderSevice;

    @Autowired
    private CacheServiceFeign cacheServiceFeign;
    @Autowired
    RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(SeckillOrderMessage message) {
        log.info("收到秒杀订单消息：{}", message);
        // 1. 校验用户信息
        User user = userServiceFeign.getUserByUid(message.getUid());
        if (user == null || user.getUid() == -999) {
            productServiceFeign.increaseStock(message.getPid(), 1); // 恢复库存
            return;
        }

        // 2. 校验商品信息
        Product product = productServiceFeign.getProductByPid(message.getPid());
        if (product == null || product.getStatus() != 1) {
            productServiceFeign.increaseStock(message.getPid(), 1); // 恢复库存
            return;
        }

        // 3. 创建正式订单
        Order order = new Order();
        order.setUid(user.getUid());
        order.setUsername(user.getUsername());
        order.setPid(message.getPid());
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);
        order.setStatus(0); // 未支付状态

        boolean addResult = orderSevice.addOrder(order);
        cacheServiceFeign.addRepeatedSeckillUser(message.getUid(), message.getPid());
        if (!addResult) {

            productServiceFeign.increaseStock(message.getPid(), 1); // 恢复库存
        }else {
//            向通知服务发送消息
            rocketMQTemplate.syncSend( NotificationTopic.SECKILL_NOTIFICATION, order);
        }
    }
}
